package examples_stc

import (
	"database/sql"
	v1config "gitee.com/scottq/go-framework/src/v1/config"
	"gitee.com/scottq/go-framework/src/v1/libs/clients/dbs"
)

type OpMysql struct {
	dbs.IDBMysql
}

func NewOpMysql(c v1config.DBConfig) (*OpMysql, error) {
	db, err := dbs.NewDBMysql(c)
	if err != nil {
		return nil, err
	}
	return &OpMysql{
		db,
	}, nil
}

func (op *OpMysql) Query() ([]map[string]interface{}, int64, error) {
	fields := []string{
		"id",
		"created_at",
		"nickname",
		"account",
	}
	where := []string{
		"id>1",
	}
	whereArgs := []interface{}{}
	orderBy := []string{
		"id desc",
	}

	list := []map[string]interface{}{}
	_, total, err := op.ExecuteSearch("admin", fields, where, whereArgs, orderBy, 1, 10,
		func(rows *sql.Rows) error {
			for rows.Next() {
				id := 0
				createdAt := ""
				nickname := ""
				account := ""

				err := rows.Scan(&id, &createdAt, &nickname, &account)
				if err != nil {
					return err
				}
				list = append(list, map[string]interface{}{
					"id":         id,
					"created_at": createdAt,
					"nickname":   nickname,
					"account":    account,
				})
			}
			return nil
		})
	if err != nil {
		return nil, 0, err
	}
	return list, total, nil
}

func (op *OpMysql) BeginTrans() (*OpMysql, error) {
	var err error

	newOp := &OpMysql{}
	newOp.IDBMysql, err = op.IDBMysql.BeginTrans()

	return newOp, err
}

func (op *OpMysql) CommitTrans() error {
	return op.IDBMysql.CommitTrans()
}

func (op *OpMysql) RollbackTrans() error {
	return op.IDBMysql.RollbackTrans()
}
